package com.example.controller;

import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RegisterController {
    @Autowired
    private UserService userService;

    //处理注册
    @PostMapping("/register")
    public String register(Model model,
                           @RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String password2){
        if (username!=null && password!=null&& password2!=null){

             if (!password.equals(password2)){//两次密码不一致
                model.addAttribute("error", "两次密码不一致！");
                model.addAttribute("username",username);
                model.addAttribute("password",password);
                model.addAttribute("password2",password2);
                return "register";
            }else {
                 //用户名不存在且两次密码一致
                int count = userService.register(username, password);
                if (count>0){
                    return "redirect:login";
                }else {
                    model.addAttribute("error", "注册失败！");
                    model.addAttribute("username",username);
                    model.addAttribute("password",password);
                    model.addAttribute("password2",password2);
                    return "register";
                }
            }
        }else {
            //用户名或密码为空
            model.addAttribute("error", "用户名或密码不能为空！");
            model.addAttribute("username",username);
            model.addAttribute("password",password);
            model.addAttribute("password2",password2);
            return "register";
        }
    }
}
